import { reactive, ref, onMounted, h } from "vue";
import { useListPage } from "@/composables/useListPage";
import { useDialog } from "@/composables/useDialog";
import { useCRUD } from "@/composables/useCRUD";
import { deviceDetection } from "@pureadmin/utils";
import api from "@/api/seller/trade/order";
import { useRoute } from "vue-router";

// 定义表单类型
interface orderFormState {
  keyword: string;
  order_status: string | number;
  create_time: string | [string, string] | null;
  update_time: string | [string, string] | null;
  page: number;
  page_size: number;
}

export function use() {
  const route = useRoute();
  const hasProcessedInitialRoute = ref(false);

  // 使用 useListPage 优化列表页面逻辑
  const {
    formState,
    pagination,
    dataList,
    loading,
    multipleSelection,
    onSearch,
    resetForm,
    handlePageChange,
    handleSizeChange,
    handleSelectionChange
  } = useListPage<orderFormState>(api, {
    keyword: "",
    order_status: "",
    create_time: "",
    update_time: "",
    page: 1,
    page_size: 10
  });

  // 使用 useDialog 优化弹窗逻辑
  const { openDialog } = useDialog();

  // 使用 useCRUD 优化 CRUD 操作
  const { read } = useCRUD(api);

  const columns: TableColumnList = [
    {
      type: "expand",
      slot: "expand"
    },
    {
      label: "状态",
      prop: "status",
      width: 100,
      slot: "status"
    },
    {
      label: "订单单号",
      prop: "order_no",
      width: 250,
      align: "left",
      slot: "order_no"
    },
    {
      label: "商品数量",
      width: 120,
      slot: "product_amount"
    },
    {
      label: "订单金额",
      prop: "original_total_amount",
      width: 120
    },
    {
      label: "下单时间",
      prop: "create_time",
      width: 180
    },
    {
      label: "更新时间",
      prop: "update_time",
      width: 180
    }
  ];
  // 处理路由中的 verify_code 参数
  if (route.query.order_no && !hasProcessedInitialRoute.value) {
    hasProcessedInitialRoute.value = true;
    const verifyCode = Array.isArray(route.query.order_no)
      ? route.query.order_no[0]
      : route.query.order_no;
    formState.keyword = verifyCode;
  }
  onMounted(() => {
    onSearch();
  });

  return {
    form: formState,
    loading,
    columns,
    dataList,
    pagination,
    multipleSelection,
    onSearch,
    resetForm,
    handlePageChange,
    handleSizeChange,
    handleSelectionChange
  };
}
